/**
 * 定义OnlineMonitorDataReportController在线监测数据展示模块
 */
(function(window, angular, undefined){
	var OnlineMonitorDataReportController = angular.module('OnlineMonitorDataReportController', ['ui.router','water.common.dateUtil','itfreer','waterCommon','OnlineMonitorDataReportService','water.common.freezeGrid']);
	
	//实时数据
	OnlineMonitorDataReportController.controller('RealTimeDataReportController',function($httpData,$NavService,$scope,$waterDataCommon,$wdp,$rootScope,$DataReportService,$freezeGridService){
		
		//去掉视频延迟函数
		if($wdp.timeout){
			clearTimeout($wdp.timeout); 
		}
		$("#lb").click();
		$scope.waterType = getWaterType();
		$scope.parmToCheckList = [];
		
		var now = new Date();
		$scope.queryDate = getOracleDateString(now);
		$scope.startHour = new Date().getHours()-1;
		$scope.endHour = new Date().getHours() + 1;
		$scope.hours = [];
		
		for(var i=0;i<24;i++){
			$scope.hours.push({
				id:i
			});
		}
		
		$scope.$on('dataPramChanged', function(event, data) {
			$scope.parmsToChar=[];
			$scope.wwtpReportParm = data;
			$scope.mn = $scope.wwtpReportParm.MN;
			$scope.getReport();
	    });
		
		function tableScroll(){
			 angular.element("#dataTableContent").bind("scroll", function(e) {
				 var top=document.getElementById("dataTableContent").scrollTop; 
					var left=document.getElementById("dataTableContent").scrollLeft; 
					document.getElementById("datatimeCloumn").scrollTop=top; 
					document.getElementById("dataHeadContent").scrollLeft=left; 
			   })
		} 
		
		function getOracleDateString(dtTmp){ 
			return dtTmp.getFullYear()+"-"+(dtTmp.getMonth()+1)+"-"+dtTmp.getDate();
		} 

		$scope.changeMonitorDevice = function(){
			if($httpData.ReportList && $httpData.ReportList.data ){
				$httpData.ReportList.data = [];
			}
			$scope.mn = $scope.wwtpReportParm.MN;
			if($scope.mn == null){
				return ;
			}
			// 打开websocket，监听设备消息
			if($scope.mn != null && $scope.mn != ""){
				$scope.websocket = $waterDataCommon.listenServer("DeviceInfo/"+$scope.mn+"/realTimeData",$scope.onWebSocketMessage);
			}
			$scope.getReport();
		}
		
		$scope.reLayout = function(domid){
			$("#"+domid).css("margin-left","170px");
		}
		
		$scope.parmsToChar = [];
		$scope.checkedParm = function($event,parmIndex){
			var checkedCount = 0;
			var checkBox = $event.target;
			for(var i=0;i<$scope.parmToCharList.length;i++){
				if($scope.parmToCharList[i].checked){
					checkedCount++;
				}
			}
			if(checkBox.checked && checkedCount >=4){
				checkBox.checked = false;
				$.messager.alert("提示","只能选择4个参数","info");
				return;
			}
			$scope.parmToCharList[parmIndex].checked = checkBox.checked;
			$scope.parmsToChar = [];
			for(var i=0;i<$scope.parmToCharList.length;i++){
				if($scope.parmToCharList[i].checked){
					$scope.parmsToChar.push($scope.parmToCharList[i]);
				}
			}
			$DataReportService.showChar($httpData.ReportList.data,'char_tb',$scope.parmsToChar);
		}
		$scope.checkErr = function(){		   
		    if($scope.startHour > $scope.endHour){
		    	$.messager.alert("提示","起始时间不能大于结束时间");
		      return false;
		    }		 
		  };
		$scope.getReport = function(){
			$scope.data = null;
			$("#listdata").idTabs();
			var parmToChecksStr =$scope.wwtpReportParm.parmToChecksStr;
			var parmToCheckList = $scope.wwtpReportParm.parmToCheckList;
			var parmToCheckList={};
			if(getWaterType()=="7"){
				parmToCheckList= $DataReportService.getParmCheckList($scope.wwtpReportParm.parmToCheckList,"real");
				var checkList=[];
				for(var i=0;i<  $scope.wwtpReportParm.parmToCheckList.length;i++){
					var parm= $scope.wwtpReportParm.parmToCheckList[i];
					if(parm.name== "011"||parm.name== "065"||parm.name== "060"||parm.name== "101"||parm.name== "PHE"){
						continue;
					}
					checkList.push(parm);
				}
				$scope.parmToCharList=checkList;
			}else{
				parmToCheckList= $DataReportService.getParmCheckList($scope.wwtpReportParm.parmToCheckList);
				$scope.parmToCharList = $scope.wwtpReportParm.parmToCheckList;
			}				
			$scope.parmToCheckList = parmToCheckList;
			if(!$scope.mn && $httpData.ReportList){
				$httpData.ReportList.data = [];
				$scope.websocket.close();
				return;
			}
		  
			if(parmToChecksStr == null || parmToChecksStr == ""){
				return;
			}
			
			if($scope.parmsToChar.length>0){
				
			}
			else{
			//图表部分，图表按需显示，勾选几个参数就显示几个参数的图标，默认勾选五个
			$scope.parmsToChar = [];
			if($scope.parmToCharList){
				for(var key =0;key < 4;key++){
					if(key > 4){
						break;
					}
					if(key > $scope.parmToCharList.length-1){
						break;
					}
					$scope.parmToCharList[key].checked = true;
					$scope.parmsToChar.push($scope.parmToCharList[key]);
				}
			}
			}
			$scope.parmToCheckList = parmToCheckList;
			var startTime = $scope.queryDate + " " + $scope.startHour + ":00:00";
			var endTime = $scope.queryDate + " " + $scope.endHour + ":00:00";
			$scope.queryObject = {"mn":$scope.mn,"parmToChecks":parmToChecksStr,"start":startTime,"end":endTime};
			$waterDataCommon.getPageRows("/DataReport/RealTime.do","ReportList",$scope.queryObject,15,1,function(data){
				$scope.$apply(function(){
					$scope.data = data;
					 //获取每个参数上下限
					$scope.limitList=$DataReportService.getParmLimit(parmToCheckList,data.limitData);
				});
			},function(){
				var data = $httpData.ReportList.data;
				var parmToCheckList = $scope.wwtpReportParm.parmToCheckList;
				$DataReportService.showChar(data,'char_tb',$scope.parmsToChar);
			});
		};
		
		$scope.onWebSocketMessage = function(data){
			if(data == null){
				return;
			}
			$scope.$apply(function(){
				var date = new Date();
				var newDataItem = {DATATIME:date.getFullYear() + "-" + (date.getMonth()+1)+"-"+date.getDate() + " " + date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()};
				for(var parm in data.deviceInfo){
					if(!parm){
						continue;
					}
					var pollItem = data.deviceInfo[parm];
					var num = new Number(pollItem.MEAS);
					newDataItem["P"+parm.toUpperCase()] = num;
				}
				
				var newData = [newDataItem];
				var oldData = $httpData.ReportList.data;
				for(var i=0;i<oldData.length-1;i++){
					newData.push(oldData[i]);
				}
				$httpData.ReportList.data = newData;
				$("#new_data_tip").fadeIn('slow',function(){
					setTimeout(function(){
						$("#new_data_tip").fadeOut('slow');
					},1000);
				});
			});
		}
		
		tableScroll();
		
		if($wdp.stationListReady == "true"){
			$scope.$emit('askDataPramChange', $scope.reportParms); 
		}
		
		$scope.waterDataCommon = $waterDataCommon;
		
	});
	//历史数据
	OnlineMonitorDataReportController.controller('HistoricalDataReportController',function($dateUtil,$stateParams,$httpData,$NavService,$scope,$waterDataCommon,$wdp,$rootScope,$DataReportService){
		//$NavService.setSelectedTab("DataMonitor.HistoricalReport");
		$httpData.HistoricalDataReportList = null;
		$scope.hours = [];
		$scope.paramsCou =true;//为true测试浓度历史数据，false为通量历史数据
		$scope.parmToCheckList = [];
		$scope.waterType = getWaterType();
		$scope.dataFlagMap = {
				'N':'一般测量',
				'D':'故障',
				'sc':'标样核查',
				'ps':'平行样',
				'ra':'加标回收',
				'cz':'校准',
				'Z':'水样不足',
				'mm':'手动监测'
		};
		
		for(var i=0;i<24;i++){
			$scope.hours.push({
				id:i
			});
		}
		$scope.stationType = "0";
		$("#lb").click();
		
		$scope.reLayout = function(domid){
			$("#"+domid).css("margin-left","170px");
		}
		$scope.checkErr = function(){		   
		    if((new Date($scope.startDate.replace(/-/g,"\/"))) > (new Date($scope.endDate.replace(/-/g,"\/")))){
		    	$.messager.alert("提示","起始时间不能大于结束时间");
		      return false;
		    }		 
		  };
		var now = new Date();
		$scope.startDate = getOracleDateString(new Date(Date.parse(now) + (86400000 * -1)));
		$scope.endDate = getOracleDateString(now);
		$scope.queryDate = getOracleDateString(now);
		$scope.startHour = new Date().getHours() - 1;
		$scope.endHour = new Date().getHours() + 1;
		if(getWaterType()=='7'){
			$scope.dataSource = '8';
		}else{
			$scope.dataSource = '3';
		}
		
		$scope.numLimit=19;
	
		function getOracleDateString(dtTmp){ 
			return dtTmp.getFullYear()+"-"+(dtTmp.getMonth()+1)+"-"+dtTmp.getDate();
		} 
		
		$scope.searchHistoricalData = function(){	
			if($scope.checkErr()==false){
				return false;
			}else{
				getReport();
			}
			
		}
		$scope.$on('dataPramChanged', function(event, data) {
			$scope.parmsToChar=[];
			$scope.wwtpReportParm = data;
			getReport();
	    });
		$scope.subIndex=function(parname){
			var index=parname.indexOf("(");
			if(index>0){
				parname=parname.substring(0,index);
			}			
			return parname;
		}
		$scope.parmsToChar = [];
		$scope.checkedParm = function($event,parmIndex){
			var checkedCount = 0;
			var checkBox = $event.target;
			for(var i=0;i<$scope.parmToCharList.length;i++){
				if($scope.parmToCharList[i].checked){
					checkedCount++;
				}
			}
			if(checkBox.checked && checkedCount >=4){
				checkBox.checked = false;
				$.messager.alert("提示","只能选择4个参数","info");
				return;
			}
			$scope.parmToCharList[parmIndex].checked = checkBox.checked;
			$scope.parmsToChar = [];
			for(var i=0;i<$scope.parmToCharList.length;i++){
				if($scope.parmToCharList[i].checked){
					$scope.parmsToChar.push($scope.parmToCharList[i]);
				}
			}
			$DataReportService.showChar($scope.data.data,'char_tb',$scope.parmsToChar);
		}
		
		function tableScroll(){ 
			 angular.element("#dataTableContent").bind("scroll", function(e) {
				 var top=document.getElementById("dataTableContent").scrollTop; 
					var left=document.getElementById("dataTableContent").scrollLeft; 
					document.getElementById("datatimeCloumn").scrollTop=top; 
					document.getElementById("dataHeadContent").scrollLeft=left; 
			   })
		} 
		//求总页数
		$scope.pages;
		$scope.pageIndex=1;
		$scope.getpage=function(){
			  var strDateStart=$scope.startDate;
			  var strDateEnd=$scope.endDate;
			   var strSeparator = "-"; //日期分隔符
			   var oDate1;
			   var oDate2;
			   var iDays;
			   oDate1= strDateStart.split(strSeparator);
			   oDate2= strDateEnd.split(strSeparator);
			   var strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
			   var strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
			   iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24)//把相差的毫秒数转换为天数 
			   $scope.pages=iDays+1;			   
		};
		//日期增、减一天
		$scope.getDay=function(datestr,str){
			//ie不支持这种方式
			//var date = new Date(datestr);
			//使用这种通用方式
			datestr=datestr.split(' ')[0];
			datestr = datestr.split('-'); 
			var date = new Date(); 
			date.setUTCFullYear(datestr[0], datestr[1] - 1, datestr[2]); 
			if(str=='add'){
				 date.setDate(date.getDate() + 2);	
			}
			else{
				date.setDate(date.getDate() - 2);
			}
            var month = date.getMonth() + 1;
            var day = date.getDate();
            return date.getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
		}
		function getFormatDate(arg) {
            if (arg == undefined || arg == '') {
                return '';
            }

            var re = arg + '';
            if (re.length < 2) {
                re = '0' + re;
            }

            return re;
        }
		//首页
		$scope.firstPage=function(){
			 $scope.pageIndex=1;
			$scope.queryObj.START = $scope.endDate + " 00:00:00";
			$scope.queryObj.END = $scope.endDate+ " 23:59:59";
				$waterDataCommon.post("/DataReport/HistoricalData.do",$scope.queryObj,function(result){
				$scope.$apply(function(){
					$scope.data = result;
				});
				$DataReportService.showChar(result.data,'char_tb',$scope.parmsToChar);
			});
			
		};
		//上一页
		$scope.prePage=function(){
			if($scope.queryObj.START==($scope.endDate+" 00:00:00")){
				return;
			}
			if($scope.pageIndex >1){
				 $scope.pageIndex-=1;
				 var st=$scope.getDay($scope.queryObj.START,"add");
				$scope.queryObj.START=st+ " 00:00:00";
				$scope.queryObj.END = st + " 23:59:59";
				$waterDataCommon.post("/DataReport/HistoricalData.do",$scope.queryObj,function(result){
					$scope.$apply(function(){
						$scope.data = result;
					});
					$DataReportService.showChar(result.data,'char_tb',$scope.parmsToChar);
				});
			}	
			else{
				return;
			}
		};
		//下一页
		$scope.nextPage=function(){
			var queryStart = $dateUtil.createDate($scope.queryObj.START);
			var viewStart = $dateUtil.createDate($scope.startDate);
			if(queryStart <= viewStart){
				return;
			}
			if($scope.pageIndex < $scope.pages){
				 $scope.pageIndex+=1;
				 var st=$scope.getDay($scope.queryObj.START,"delete");
				$scope.queryObj.END = $scope.queryObj.START.split(" ")[0] + " 23:59:59";
				$scope.queryObj.START=st+ " 00:00:00";
				$waterDataCommon.post("/DataReport/HistoricalData.do",$scope.queryObj,function(result){
					$scope.$apply(function(){
						$scope.data = result;
					});
					$DataReportService.showChar(result.data,'char_tb',$scope.parmsToChar);
				});
			}
			else{
				return;
			}
		};
		//尾页
		$scope.lastPage=function(){
			 $scope.pageIndex=$scope.pages;
			$scope.queryObj.START = $scope.startDate + " 00:00:00";
			$scope.queryObj.END = $scope.startDate + " 23:59:59";
				$waterDataCommon.post("/DataReport/HistoricalData.do",$scope.queryObj,function(result){
				$scope.$apply(function(){
					$scope.data = result;
				});
				$DataReportService.showChar(result.data,'char_tb',$scope.parmsToChar);
			});
		};
		//历史信息获取数据
		function getReport(){
			
			if((new Date($scope.startDate.replace(/-/g,"\/"))) > (new Date($scope.endDate.replace(/-/g,"\/")))){
			      alert("起始时间不能大于结束时间");
			      return false;
			    }
			
			$scope.data = null;
			var queryObj = {};
			
			$("#listdata").idTabs();
			var wwtpId = $scope.wwtpReportParm.WWTPID;
			var stationId = $scope.wwtpReportParm.STATION_ID;
			var parmToChecksStr = $scope.wwtpReportParm.parmToChecksStr;
			var mn =$scope.wwtpReportParm["MN"+$scope.stationType];
			var dataType = $scope.dataType;
			if(mn == null){
				mn = $scope.wwtpReportParm.MN;
			}
			if(mn == null){
				return ;
			}
			
			if(!wwtpId && !stationId){
				return;
			}
			if(parmToChecksStr == ""){
				return;
			}
			if($stateParams.paramsCou==false){
				$scope.paramsCou=$stateParams.paramsCou;
			}
			var parmToCheckList={};
			if($scope.paramsCou==true){
				//浓度
				parmToCheckList = $DataReportService.getParmCheckList($scope.wwtpReportParm.parmToCheckList,$scope.dataSource);				
			}else{
				//通量
				vparmToCheckList = $DataReportService.getParmCheckCouList($scope.wwtpReportParm.parmToCheckList,$scope.dataSource);
			}
			$scope.parmToCheckList = parmToCheckList;
			$scope.parmToCharList = $scope.wwtpReportParm.parmToCheckList;
						
            if($scope.parmsToChar.length>0){
				
			}
			else{
				//图表部分，图表按需显示，勾选几个参数就显示几个参数的图标，默认勾选五个
				$scope.parmsToChar = [];
				for(var key =0;key < 4;key++){
					if(key > 4){
						break;
					}
					if(key > $scope.parmToCharList.length-1){
						break;
					}
					$scope.parmToCharList[key].checked = true;
					$scope.parmsToChar.push($scope.parmToCharList[key]);
				}
			}
			
			// 如果 
			if($scope.dataSource == '1' || $scope.dataSource == '2'){
				queryObj.START = $scope.queryDate +" " + $scope.startHour + ":00:00";
				queryObj.END = $scope.queryDate + " " + $scope.endHour + ":59:59";
			}
			else if($scope.dataSource == '4' || $scope.dataSource == '3' || $scope.dataSource == '6'|| $scope.dataSource == '7'|| $scope.dataSource == '8'){
				queryObj.START = $scope.startDate + " 00:00:00";
				queryObj.END = $scope.endDate + " 23:59:59";
				if($scope.dataSource == '3' ){					
					var startDate = new Date($scope.startDate.replace(/-/g,"/") + " 00:00:00");
					var endDate = new Date($scope.endDate.replace(/-/g,"/") + " 23:59:59");
					
					var  dateDiff = (endDate - startDate) / 1000 / 60 / 60 / 24;
					
					if(dateDiff > 2){
						startDate.setUTCFullYear(endDate.getFullYear(),endDate.getMonth(),endDate.getDate())
						startDate.setDate(startDate.getDate() - 2);
					}
					queryObj.START = startDate.Format('yyyy-MM-dd hh:mm:ss');
					queryObj.END = endDate.Format('yyyy-MM-dd hh:mm:ss');
				}
			}
			
			switch($scope.dataSource){
				case '1':
					$scope.numLimit=19;
					break;
				case '2':
					$scope.numLimit=16;
					break;
				case '3':
					$scope.numLimit=13;
					break;
				case '4':
				case '5':
					$scope.numLimit=10;
					break;
			}
			
			queryObj.WWTP_ID = wwtpId;
			if(wwtpId){
				queryObj.FLOW_TYPE = $scope.flowType;
			}
			queryObj.STATION_ID = stationId;
			queryObj.DATA_SOURCE = $scope.dataSource;
			if($scope.paramsCou==true){
				queryObj.parmToChecks = parmToChecksStr;
			}else{
				$scope.parmsitem=parmToChecksStr.split(",");
				
				var parm="";
				for(var i=0;i<$scope.parmsitem.length;i++){
					if($scope.parmsitem[i]!='001'&&$scope.parmsitem[i]!='B01TOTAL'&&$scope.parmsitem[i]!='"PHTEM"'){
						parm=parm+","+$scope.parmsitem[i];
					}
				}
				queryObj.parmToChecks=parm;
			}
			queryObj.mn = mn;
			queryObj.dataType = $scope.dataType;
			queryObj.WATER_TYPE = $scope.waterType;
			$scope.queryObj=queryObj;
			//查询相差几天
			$scope.getpage();
			$scope.pageIndex=1;
			if($scope.paramsCou==true){
				//获取浓度历史数据
				$waterDataCommon.post("/DataReport/HistoricalData.do",queryObj,function(result){
					$scope.$apply(function(){
						$scope.data = result;
						 //获取每个参数上下限
						$scope.limitList=$DataReportService.getParmLimit(parmToCheckList,result.limitData);
					});
					$DataReportService.showChar(result.data,'char_tb',$scope.parmsToChar);
				});
			}else{
				//获取通量历史数据
				$waterDataCommon.post("/DataReport/historicalFluxData.do",queryObj,function(result){
					$scope.$apply(function(){
						$scope.data = result;
					});
					$DataReportService.showChar(result.data,'char_tb',$scope.parmsToChar);
				});
			}
		}
		//导出
		$scope.exportHistoricalExcel = function (){
			var obj={};
			if($scope.paramsCou==true){
				var checkList =$DataReportService.getParmCheckList($scope.wwtpReportParm.parmToCheckList);
			}else{
				var checkList =$DataReportService.getParmCheckCouList($scope.wwtpReportParm.parmToCheckList);
			}
			var heads=['时间'];
			var fields=['DATATIME'];
			angular.forEach(checkList,function(value,key){
				heads.push(value.headText);
				fields.push(value.attrName);
			});
			obj.HEADERS = heads;
			obj.FIELDS = fields;
			obj.WWTP_ID=$scope.wwtpReportParm.WWTPID;
			var mn = $scope.wwtpReportParm["MN"+$scope.stationType];
			if(mn == null){
				mn =$scope.wwtpReportParm.MN;
			}
			if(mn == null){
				return ;
			}
			if(obj.WWTP_ID){
				obj.FLOW_TYPE=$scope.flowType;
			}
			
			obj.STATION_ID=$scope.wwtpReportParm.STATION_ID;
			obj.START = $scope.startDate+" 00:00:00";
			obj.END = $scope.endDate+" 23:59:59";
			obj.DATA_SOURCE = $scope.dataSource;
			obj.mn = mn;
			obj.parmToChecks=$scope.wwtpReportParm.parmToChecksStr;
			
			var s = obj.START.split('-');
			var e = obj.END.split('-');
			var start = s[0] + "年" + s[1] + "月" + s[2] + "日--";
			var end = e[0] + "年" +e[1] + "月" + e[2] + "日";
			
			var src = "实时";
			if ("2"==$scope.dataSource)
				src = "五分钟";
			else if ("3"==$scope.dataSource)
				src = "小时";
			else if ("4"==$scope.dataSource)
				src = "日均值";
			else if ("5"==$scope.dataSource)
				src = "日均消减";
			
			obj.FILENAME = start+end +'历史数据('+src+').xls';
		
			var queryString = $waterDataCommon.jsonTostring(obj);
			if($scope.paramsCou==true){
				window.open(getBasePath()+"/DataReport/exportHistoricalExcel.do?"+queryString);
			}else{
				window.open(getBasePath()+"/DataReport/exportHistoricalCouExcel.do?"+queryString);
			}
		}
		
		if($wdp.stationListReady=="true"){
			$scope.$emit('askDataPramChange', $scope.reportParms); 
		}
		
		tableScroll();
		$scope.waterDataCommon = $waterDataCommon;
	});
	//报表
	OnlineMonitorDataReportController.controller('ReportController',function($ReportService,$httpData,$NavService,$scope,$waterDataCommon,$wdp,$rootScope,$DataReportService,$stateParams){		
		$NavService.setSelectedTab("DataMonitor.RealTimeReport");		
		$httpData.reportList = null;
		$scope.parmToCheckList = [];
		
		$("#Reportlb").click();
		$scope.paramsCou =false;//为true是通量数据，false为浓度数据
		if($stateParams.paramsCou == true){
			$scope.paramsCou=$stateParams.paramsCou;
		}
		
		$ReportService.setSelectedTabSecond("ReportSecondBase");
		$ReportService.setSelectedTab("Report.statistics.dayReport");
		$NavService.setSelectedTab("DataMonitor.ReportTotal");
		$scope.stationType = "1"; 
		$scope.dataType;
		$scope.numLimit = 13;
		
		var titleDict = {
				"day":"日",
				"week":"周",
				"month":"月",
				"quarter":"季",
				"year":"年"
		}
		
		function tableScroll(){ 
			 angular.element("#dataTableContent").bind("scroll", function(e) {
				 var top=document.getElementById("dataTableContent").scrollTop; 
					var left=document.getElementById("dataTableContent").scrollLeft; 
					document.getElementById("datatimeCloumn").scrollTop=top; 
					document.getElementById("dataHeadContent").scrollLeft=left; 
			   })
		} 
		
		//初始化日期
		$scope.initQuery = function(dataType){
			$scope.dataType = dataType;
			if($scope.dataType == "day"){
				$scope.numLimit=13;
			}
			else if($scope.dataType == "month"){
				$scope.numLimit=7;
			}
			// 日查询条件
			if(dataType == "day"){
				var nowDate = new Date();
				$scope.daytime=nowDate.getFullYear()+"-"+(nowDate.getMonth()+1)+"-"+(nowDate.getDate()-1);
				$scope.endtime=nowDate.getFullYear()+"-"+(nowDate.getMonth()+1)+"-"+nowDate.getDate();
			}
			// 周查询条件，其中年份是公用的
			$scope.yearlist=[];
			var currentYear=(new Date()).getFullYear();
			for(var i=0;i<4;i++){
				$scope.yearlist.push({
					name:currentYear-i+"年",
					value:currentYear-i+""
				});
			}; 
			$scope.selectYear=currentYear+"";
			$scope.changeYear($scope.selectYear);
			// 月查询条件
			$scope.monthlist=[];
			for(var i=1;i<=12;i++){
				$scope.monthlist.push({
					name:i+"月",
					value:""+i
				});
			};
			$scope.selectMonth=((new Date()).getMonth() + 1)+"";
			// 季度查询条件
			$scope.quarterslist=[
			                 {name:"第1季度",value:"1"},
			                 {name:"第2季度",value:"2"},
			                 {name:"第3季度",value:"3"},
			                 {name:"第4季度",value:"4"}
			                ];
			$scope.selectQuarter = ""+ (Math.floor(((new Date).getMonth()+1)/4)+1);
			
			$scope.getReport();
		}
		$scope.isShowAvg=true;
		$scope.isShowElecFactory=false;
		$scope.showStatisType = function(type) {
			if(type=='avg') {
				$scope.isShowAvg=true;
				$scope.isShowElecFactory=false;
			}
			if(type=='elecFactory') {
				$scope.isShowElecFactory=true;
				$scope.isShowAvg=false;
			}
		}
		// 选择年份更新周信息
		$scope.changeYear = function(year){
			$scope.weeklist = $DataReportService.getYearWeek(year);
			$scope.selectWeek= $scope.weeklist[0].value;
			for(var i=0;i<$scope.weeklist.length;i++){
				var week = $scope.weeklist[i];
				if(week.today){
					$scope.selectWeek = week.value;
				}
			}
		}
		
		$scope.showChar = function(){
			var data = $httpData.reportList.data;
			$DataReportService.showChar(data,'char_tb',$scope.parmsToChar);
		}
		
		$scope.$on('dataPramChanged', function(event, data) {
			$scope.parmsToChar=[];
			$scope.wwtpReportParm = data;
			$scope.getReport();
	    });
		
		$scope.parmsToChar = [];
		$scope.checkedParm = function($event,parmIndex){
			var checkedCount = 0;
			var checkBox = $event.target;
			for(var i=0;i<$scope.parmToCharList.length;i++){
				if($scope.parmToCharList[i].checked){
					checkedCount++;
				}
			}
			if(checkBox.checked && checkedCount >=4){
				checkBox.checked = false;
				$.messager.alert("提示","只能选择4个参数","info");
				return;
			}
			$scope.parmToCharList[parmIndex].checked = checkBox.checked;
			$scope.parmsToChar = [];
			for(var i=0;i<$scope.parmToCharList.length;i++){
				if($scope.parmToCharList[i].checked){
					$scope.parmsToChar.push($scope.parmToCharList[i]);
				}
			}
			$DataReportService.showChar($httpData.reportList.data,'char_tb',$scope.parmsToChar);
		}
		
		function getQueryObj(){
			if($scope.dataType == null){
				return null;
			}
			if(!$scope.wwtpReportParm){
				return null;
			}
			var mn = $scope.wwtpReportParm["MN"+$scope.stationType];
			if(mn == null){
				mn = $scope.wwtpReportParm.MN;
			}
			if(mn == null){
				return null;
			}
			var queryObj = {};
			if($scope.dataType == "day"){
				queryObj.startDate = $scope.daytime + " 00:00:00";
				queryObj.endDate = $scope.daytime + " 23:59:59";
			}
			else if($scope.dataType == "week"){
				var weekInfo=$scope.selectWeek.split(",");
				queryObj.startDate = weekInfo[0] + " 00:00:00";
				queryObj.endDate = weekInfo[1] + " 23:59:59";
			}
			else if($scope.dataType == "month"){
				var date = new Date();
				date.setFullYear($scope.selectYear);
				date.setMonth(parseInt($scope.selectMonth) - 1);
				date.setDate(1);
				date.setMonth(parseInt($scope.selectMonth));
				
				queryObj.startDate =$scope.selectYear + "-" + $scope.selectMonth + "-01" + " 00:00:00";
				//获取每个月最后一天
				var end_day = new Date($scope.selectYear,$scope.selectMonth,0); 
				queryObj.endDate =$scope.selectYear + "-" + $scope.selectMonth + "-"+end_day.getDate() + " 23:59:59";
				
			}
			else if($scope.dataType == "quarter"){
				var startMonth = 1 + (parseInt($scope.selectQuarter) - 1) * 3;
				queryObj.startDate =$scope.selectYear + "-" + startMonth + "-01" + " 00:00:00";
				var date=new Date($scope.selectYear,(startMonth+2),0);
				queryObj.endDate =$scope.selectYear + "-" + (startMonth+2) + "-"+date.getDate() + " 23:59:59";					
				
			}
			else if($scope.dataType == "year"){
				var startMonth = 1 + (parseInt($scope.selectQuarter) - 1) * 3;
				queryObj.startDate =$scope.selectYear + "-01-01" + " 00:00:00";
				queryObj.endDate =$scope.selectYear  + "-12-31" + " 23:59:59";
			}
			
			queryObj.parmToChecks =  $scope.wwtpReportParm.parmToChecksStr;
			queryObj.mn = mn;
			queryObj.dataType = $scope.dataType;
			
			if(queryObj.parmToChecks == ""){
				return null;
			}
			
			queryObj.isCOU = $scope.paramsCou;
			return queryObj;
		}
		$scope.getReport = function(){
			var queryObj = getQueryObj();
			if(queryObj == null ){
				return;
			}
			
			
			$scope.parmToCheckList = $DataReportService.getParmCheckList($scope.wwtpReportParm.parmToCheckList);
			
			//如果是排放量的话，要另外获取参数信息
			if(queryObj.isCOU){
				$scope.parmToCheckList = $DataReportService.getParmCheckCouList($scope.wwtpReportParm.parmToCheckList,$scope.dataSource);
			}
			
			$scope.parmToCharList = $scope.wwtpReportParm.parmToCheckList;		
			if($scope.parmsToChar.length>0){
				
			}
			else{
				//图表部分，图表按需显示，勾选几个参数就显示几个参数的图标，默认勾选五个
				$scope.parmsToChar = [];
				for(var key =0;key < 4;key++){
					if(key > 4){
						break;
					}
					if(key > $scope.parmToCharList.length-1){
						break;
					}
					$scope.parmToCharList[key].checked = true;
					$scope.parmsToChar.push($scope.parmToCharList[key]);
				}
			}
			//解决数据不一样是滚动时间与数据不对齐
			$("#dataTableContent").animate({scrollTop:0}, 1000);
			
			$waterDataCommon.getPageRows("/DataReport/getReport.do","reportList",queryObj,1,1,function(result){
				$("#listdataReport").idTabs();
				$scope.itemRow = result.item;
				$scope.totalRow = result.total;
				$scope.pollutantRow = result.pollutant;
				$scope.comprehensivePollutIndexRow = result.comprehensivePolluteIndex;
				$scope.$apply(function(){
					$scope.data = result;
					$DataReportService.showChar(result.data,"char_tb",$scope.parmsToChar);
					 //获取每个参数上下限
					$scope.limitList=$DataReportService.getParmLimit($scope.parmToCheckList,result.limitData);
				});
			});
		}		
		//报表导出
		$scope.exportExcel=function(){
			var obj= getQueryObj();
			
			var checkList =$DataReportService.getParmCheckList($scope.wwtpReportParm.parmToCheckList);
			
			var heads=['时间'];
			var fields=['DATATIME'];
			angular.forEach(checkList,function(value,key){
				heads.push(value.headText);
				fields.push(value.attrName);
			});
			obj.HEADERS = heads;
			obj.FIELDS = fields;
			
			var stationName = "";
			var title = "";
			obj.WWTP_ID=$scope.wwtpReportParm.WWTPID;
			if(obj.WWTP_ID){
				stationName = '污水处理厂：'+$scope.wwtpReportParm.WWTP_NAME;
				obj.FLOW_TYPE=$scope.flowType;
				if($scope.stationType=='1'){
					stationName+='(出水口)';
				}else{
					stationName+='(入水口)';
				}
				title = '污水处理厂数据'+titleDict[$scope.dataType]+'报表';
			}else{
				stationName = '站点名称：'+$scope.wwtpReportParm.STATION_NAME;
				if(getWaterType()=='0'){
					title = '污水在线监测数据'+titleDict[$scope.dataType]+'报表';
				}
				else if(getWaterType()=='1'){
					title = '地表水环境质量数据'+titleDict[$scope.dataType]+'报表';
				}
				else{
					title=titleDict[$scope.dataType]+'报表';
				}
			}
			obj.NAME=stationName;
			obj.TITLE = title;	
			
			if($scope.dataType == "day"){
				var days = $scope.daytime.split('-');
				obj.FILENAME=days[0]+'年'+days[1]+'月'+days[2]+'日报表.xls';
			}
			else if($scope.dataType == "week"){
				var weekInfo=$scope.selectWeek.split(",");
				
				var day1 = weekInfo[0].split('-');
				var day2 = weekInfo[1].split('-');
				var s1 = $scope.selectYear+'年第'+weekInfo[2]+'周';
				var s2 = day1[1]+'月'+day1[2]+'日--';
				var s3 = day2[1]+'月'+day2[2]+'日';
				obj.FILENAME=s1+s2+s3+'报表.xls';
			}
			else if($scope.dataType == "month"){
				obj.FILENAME=$scope.selectYear+'年'+$scope.selectMonth+'月报表.xls';
			}
			else if($scope.dataType == "quarter"){
				obj.FILENAME=$scope.selectYear+'年第'+$scope.selectQuarter+'季度报表.xls';
			}
			else if($scope.dataType == "year"){
				obj.FILENAME=$scope.selectYear+'年报表.xls';
			}
			
			var now = new Date();
			obj.TIME='上报日期：'+now.getFullYear()+"年"+(now.getMonth()+1)+"月"+now.getDate()+"日";
		
			var queryString = $waterDataCommon.jsonTostring(obj);
			window.open(getBasePath()+"/DataReport/exportReportExcel.do?"+queryString);
		};
		
		if($wdp.stationListReady == "true"){
			$scope.$emit('askDataPramChange', $scope.reportParms); 
		}
		
		tableScroll();
		$scope.initQuery("day");
	});
	//消减量
	OnlineMonitorDataReportController.controller('AmountReportController',function($httpData,$DataReportService,$scope,$ReportService,$waterDataCommon,$httpData,$queryObj,$wdp,$rootScope){
		$("#listdata").idTabs();
		$ReportService.setSelectedTab("Report.statistics.amount");
		$("input[name='parmToChar']").bind("click",function(){
			$scope.showChar();
		});
		var yearlist=$scope.yearlist={};
		yearlist.year=[];
		var nowDate = new Date();
		var y=nowDate.getFullYear();
		for(var i=0;i<4;i++){
			var obj=new Object();
			obj.name=y-i+"年";
			obj.value=y-i+"";
			yearlist.year.push(obj);
		}; 
		yearlist.codeValue=nowDate.getFullYear()+"";
		var monthlist=$scope.monthlist={};
		monthlist.names=[
		                 {name:"01月",value:"01"},
		                 {name:"02月",value:"02"},
		                 {name:"03月",value:"03"},
		                 {name:"04月",value:"04"},
		                 {name:"05月",value:"05"},
		                 {name:"06月",value:"06"},
		                 {name:"07月",value:"07"},
		                 {name:"08月",value:"08"},
		                 {name:"09月",value:"09"},
		                 {name:"10月",value:"10"},
		                 {name:"11月",value:"11"},
		                 {name:"12月",value:"12"}
		                ];
		var m=nowDate.getMonth()+1;
		if(m<10)
		{
			m="0"+m;
		}
		m = m + "";
		monthlist.codeValue = m;
		var wwtpReportParm;
		
		$scope.showChar = function(){
			
			var data = $httpData.amountList.data;
			var parmToCheckList = $scope.wwtpReportParm.parmToCheckList;
			$DataReportService.showChar(data,'tb',parmToCheckList);
		}
		
		$scope.querydata=function(){
			var wwtpId = $scope.wwtpReportParm.WWTPID;
			var parmToChecksStr = $scope.wwtpReportParm.parmToChecksStr;
			var parmToCheckList = $scope.wwtpReportParm.parmToCheckList;
			
			if(!wwtpId){
				return;
			}
			if(parmToChecksStr == ""){
				return;
			}
			$scope.parmToCheckList = parmToCheckList;
			$waterDataCommon.getPageRows("/DataReport/Amount.do","amountList",{"wwtpid":wwtpId,"yearstr":yearlist.codeValue,"monthstr":monthlist.codeValue,"flowType":$scope.flowType,"parmToChecks":parmToChecksStr},1,1,function(d){
				$scope.showChar(d.data);
			});
		};

		if($scope.wwtpReportParmWatch){
			$scope.wwtpReportParmWatch();
		}
		$scope.wwtpReportParmWatch = $rootScope.$watch(function(){return $scope.wwtpReportParm;},function(){
			if($scope.wwtpReportParm){
				$scope.querydata();
			};
        },true);
	});
	/**
	 * 数据一致性
	 */
	OnlineMonitorDataReportController.controller('DataReportComparison',function($state,
			$scope,$waterDataCommon,$wdp,$rootScope,$httpData,$DataReportService){
		$scope.queryObject={};
		$scope.allStationSelected =true;
		$scope.firstQuery = true;
		$scope.$on('dataPramChanged', function(event, data) {
			if($scope.firstQuery){
				$scope.allStationSelected = true;
			}
			else{
				$scope.allStationSelected = false;
			}
			$scope.firstQuery = false;
			$scope.STATION_ID = data.STATION_ID;
			$scope.DataReportComparisonList();
	    });
		$scope.DataReportComparisonList = function(){
			var date=new Date();
			if($scope.queryObj.start==undefined||$scope.queryObj.start==null){
				var month="";
				var day="";
				var curMonthDays = new Date(date.getFullYear(), (date.getMonth()), 0).getDate();//获取当月有多少天
				if(date.getDate()-1==0){
					month=date.getMonth();
					day=curMonthDays;
				}else{
					month=date.getMonth()+1;
					day=date.getDate()-1;
				}
				$scope.queryObj.start=date.getFullYear() + "-"+ month + "-" + day;
				$scope.queryObj.end=date.getFullYear() + "-"+ (date.getMonth()+1) + "-" + date.getDate();
			}
			$scope.queryObj.STATION_ID = $scope.STATION_ID;
			if($scope.allStationSelected == true){
				delete $scope.queryObj.STATION_ID;
			}
			var waterType = getWaterType();
			$scope.queryObj.WATER_TYPE = waterType;
			$waterDataCommon.getPageRows("/DataReport/queryCoherencedata.do","DataReportComparisonList",$scope.queryObj,1,1,function(d){
				console.log(d);
			}); 
		}
		//导出
		$scope.ComparisonExcel=function(data){
			var obj={};
			obj.STATION_ID=$scope.STATION_ID;
			if($scope.allStationSelected == true){
				delete obj.STATION_ID;
			}
			obj.start =$scope.queryObj.start;
			obj.end =$scope.queryObj.end;
			
			obj.username=$scope.queryObj.username;
			var queryString = $waterDataCommon.jsonTostring(obj);
			window.open(getBasePath()+"/DataReport/exportCoherencedataPDF.do?"+queryString);
		};
		$scope.checkErr = function(){		   
		    if((new Date($scope.queryObj.start.replace(/-/g,"\/"))) > (new Date($scope.queryObj.end.replace(/-/g,"\/")))){
		      alert("起始时间不能大于结束时间");
		      return false;
		    }		 
		  };
		  
		 $scope.Mathabs=function(rtd,value){
			var absrtd=0;
			absrtd=Math.abs(rtd-value);
			return absrtd;
		  }
		//广播，如果数据发生改变，则执行监听里面的方法
		if($wdp.stationListReady == "true"){
			$scope.$emit('askDataPramChange', $scope.reportParms); 
		}
	});	
	//导航控制器
	OnlineMonitorDataReportController.controller('DataReportNavController',function($httpData,$scope,$waterDataCommon,$httpData,$queryObj,$wdp,$rootScope,$state){
		
		if($wdp.viewValue.stateWatch){
			$wdp.viewValue.stateWatch();
		}
		$wdp.viewValue.stateWatch = $rootScope.$watch(function(){return $state.current;},function(){
			$scope.stateName = $state.current.name;
        },true);
	});
}(window, angular));	